package cn.ycbjie.ycaudioplayer.newpack.linkagescroll;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.nineoldandroids.animation.ObjectAnimator;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.ycbjie.ycaudioplayer.R;
import cn.ycbjie.ycaudioplayer.base.BaseAppHelper;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.adapter.ListFragmentPagerAdapter;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.adapter.ViewPagerAdapter;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment.ListFragment;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment.ListFragment2;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment.ListFragment3;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.listener.DoubleClickListener;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.utils.ScreenUtils;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.widget.BannerViewPager;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.widget.PagerSlidingTabStrip;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.widget.ListViewPager;
import cn.ycbjie.ycaudioplayer.service.PlayService;
import cn.ycbjie.ycaudioplayer.ui.music.local.model.AudioMusic;
import cn.ycbjie.ycaudioplayer.util.musicUtils.CoverLoader;

public class MainActivity extends AppCompatActivity implements AppBarLayout.OnOffsetChangedListener {

    @BindView(R.id.scroll_Viewpager)
    ListViewPager scrollViewpager;
    @BindView(R.id.scroll_imageBanner)
    BannerViewPager scrollImageBanner;
    @BindView(R.id.scroll_imageBanner_layout)
    RelativeLayout scrollImageBannerLayout;
    @BindView(R.id.scroll_toolbar)
    Toolbar scrollToolbar;

    @BindView(R.id.scroll_pagerSlidingTabStrip)
    PagerSlidingTabStrip scrollPagerSlidingTabStrip;
    @BindView(R.id.scroll_collapsingToolbarLayout)
    CollapsingToolbarLayout scrollCollapsingToolbarLayout;
    @BindView(R.id.scroll_appbar)
    AppBarLayout scrollAppbar;
    @BindView(R.id.scroll_coordinatorLayout)
    CoordinatorLayout scrollCoordinatorLayout;
    @BindView(R.id.scroll_swipeRefreshLayout)
    SwipeRefreshLayout scrollSwipeRefreshLayout;

    @BindView(R.id.lins)
    LinearLayout lins;

    @BindView(R.id.iv_play_bar_cover)
    ImageView ivPlayBarCover;
    @BindView(R.id.tv_play_bar_title)
    TextView tvPlayBarTitle;
    @BindView(R.id.tv_play_bar_artist)
    TextView tvPlayBarArtist;
    @BindView(R.id.iv_play_bar_play)
    ImageView ivPlayBarPlay;
    @BindView(R.id.pb_play_bar)
    ProgressBar pbPlayBar;
    @BindView(R.id.tv_summary)
    TextView tv_summary;
    @BindView(R.id.tv_updata_time)
    TextView tv_updata_time;
    @BindView(R.id.img_titleimg)
    ImageView img_titleimg;
    @BindView(R.id.tv_datitle)
    TextView datitle;

    private ListFragment fragment1;
    private ListFragment2 fragment2;
    private ListFragment3 fragment3;

    private List<Fragment> fragmentList = new ArrayList<>();
    private List<String> tabList = new ArrayList<>();
    private ListFragmentPagerAdapter listStripFragmentPagerAdapter;
    private FragmentPagerAdapter fragmentPagerAdapter;

    private int devider = 0;
    private int curTab = 0;
    private int tabScroll;
    private int scrollOffset = 4444;
    private int scrollOffsetSquare = 0;
    private int scrollOffsetAttention = 0;
    private String myid,title,picurl,created,summary;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
//        Intent intent = new Intent();
//        intent.setClass(this,com.ycbjie.)
        Intent intent = getIntent();
        myid = intent.getStringExtra("id");
        title  = intent.getStringExtra("title");
         picurl= intent.getStringExtra("picurl");
        created= stampToDate(intent.getStringExtra("created"));
        summary = intent.getStringExtra("summary");

        datitle.setText(title);
        tv_updata_time.setText(created+"更新");
        tv_summary.setText(summary);

        String uri = picurl;
        if(uri.startsWith("https")) {
            uri = uri.substring(0, 4) + uri.substring(5, uri.length());
        }



//        final ObjectAnimator anim = ObjectAnimator.ofInt(img_titleimg, "ImageLevel", 0, 10000);
//        anim.setDuration(800);
//        anim.setRepeatCount(ObjectAnimator.INFINITE);
//        anim.start();

        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.default_cover);
        Glide.with(this)
                .load(uri)
                .apply(options)

                .into(img_titleimg);

        devider = ScreenUtils.dip2px(this, 5);

        scrollCollapsingToolbarLayout.setEnabled(false);

        resolveBanner();

        resolveViewPager();

        setListener();


        /**这是tab的高度，用来设置此高度后tab可以停靠*/
        int height = (int) getResources().getDimension(R.dimen.banner_strip_height);

        setViewHeight(scrollToolbar, ViewGroup.LayoutParams.MATCH_PARENT, height);
//        setViewHeight(scrollToolbar2, ViewGroup.LayoutParams.MATCH_PARENT, height);

        tabScroll = ScreenUtils.getScreenWidth(this) / 5;

        scrollViewpager.setTouchPadding(height);

        onChangeImpl(getPlayService().getPlayingMusic());
    }

    private String stampToDate(String GMT) {
        String createTime = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
//        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(GMT);
            createTime = sdf2.format(date);
//            holder.tvProbationTime.setText("申请于" + createTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }


//        long lt = Long.parseLong(GMT)+8*3600;
//        String res = null;
//        try {
//            SimpleDateFormat  sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
////            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//            Timestamp now = new Timestamp(GMT,sf);// 获取系统当前时间
//java.sql.Timestamp c = getTi
//            res = sdf.format(lt*1000);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        return createTime;
    }

    /**
     * 获取到播放音乐的服务
     *
     * @return PlayService对象
     */
    public PlayService getPlayService() {
        PlayService playService = BaseAppHelper.get().getPlayService();
        if (playService == null) {
            throw new NullPointerException("play service is null");
        }
        return playService;
    }


    public void onChangeImpl(AudioMusic music) {
        if (music == null) {
            return;
        }
        Bitmap cover = CoverLoader.getInstance().loadThumbnail(music);
        ivPlayBarCover.setImageBitmap(cover);
        tvPlayBarTitle.setText(music.getTitle());
        tvPlayBarArtist.setText(music.getArtist());
        boolean isplaying = getPlayService().isPlaying();
        boolean ispre = getPlayService().isPreparing();
        boolean isdef = getPlayService().isDefault();

        ivPlayBarPlay.setSelected(getPlayService().isPlaying() || getPlayService().isPreparing());
        //更新进度条
        pbPlayBar.setMax((int) music.getDuration());
        pbPlayBar.setProgress((int) getPlayService().getCurrentPosition());


        /*点击MainActivity中的控制器，如何更新musicFragment中的mLocalMusicFragment呢？*/
//        if (mMusicFragment != null && mMusicFragment.isAdded()) {
//            mMusicFragment.onItemPlay();
//        }
    }

    /**
     * 这是banner数据
     */
    private void resolveBanner() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            list.add("test");
        }
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this, list);
        scrollImageBanner.setAdapter(viewPagerAdapter);
        /**
         * viewpager和父布局都设置了 android:clipChildren="false"
         * 这里设置了类似画廊效果
         * */

        scrollImageBanner.setPageMargin(ScreenUtils.dip2px(this, 20));
        scrollImageBanner.setSwipeRefreshLayout(scrollSwipeRefreshLayout);
        scrollImageBanner.setOffscreenPageLimit(3);
        scrollImageBanner.setCurrentItem(1);
//        LinearLayout linear=(LinearLayout) findViewById(R.id.base_tool_bar);
//        Toolbar toolbar = findViewById(R.layout.base_tool_bar);
//        Button bt = new Button(this);
//        bt.setText("aaaa");
//        scrollSwipeRefreshLayout.addView(bt,0);
    }


    private void resolveViewPager() {
        /**设置了tab的样式*/
        scrollPagerSlidingTabStrip.setShouldExpand(true);
        scrollPagerSlidingTabStrip.setDividerColor(Color.WHITE);
        scrollPagerSlidingTabStrip.setIndicatorColor(Color.TRANSPARENT);
        scrollPagerSlidingTabStrip.setUnderlineColor(Color.TRANSPARENT);
        scrollPagerSlidingTabStrip.setTabTextSelectColor(getResources().getColor(R.color.style_color_main));


        fragment1 = new ListFragment(myid);
        fragment2 = new ListFragment2(myid);
        fragment3 = new ListFragment3(myid);
        fragment1.setDevider(devider);
        fragment2.setDevider(devider);
        fragment1.setSwipeRefreshLayout(scrollSwipeRefreshLayout);
        fragment2.setSwipeRefreshLayout(scrollSwipeRefreshLayout);

        fragmentList.add(fragment1);
        fragmentList.add(fragment2);
        fragmentList.add(fragment3);
//        fragmentList.add(fragment1);
        tabList.add("节目");
        tabList.add("详情");
        tabList.add("推荐");
//        tabList.add("找相似");

        scrollViewpager.setAdapter(fragmentPagerAdapter);
        scrollViewpager.setOffscreenPageLimit(3);
        scrollViewpager.setSwipeRefreshLayout(scrollSwipeRefreshLayout);

        listStripFragmentPagerAdapter = new ListFragmentPagerAdapter(getSupportFragmentManager(), fragmentList, tabList);
        initFragmentPager();

    }

    public void initFragmentPager() {
        scrollViewpager.setAdapter(listStripFragmentPagerAdapter);
        scrollPagerSlidingTabStrip.setViewPager(scrollViewpager);
        scrollPagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {

            }

            @Override
            public void onPageSelected(int i) {
                /**不同的recyclerView的列表对应的位置不同，需要处理对应的顶部banner是否隐藏*/
                curTab = i;
                scrollAppbar.removeOnOffsetChangedListener(MainActivity.this);
                int scrollHeight = (i == 0) ? scrollOffsetSquare : scrollOffsetAttention;
                if (scrollHeight == -scrollAppbar.getTotalScrollRange()) {
                    CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams)
                            scrollAppbar.getLayoutParams()).getBehavior();
//                    behavior.onNestedPreScroll(scrollCoordinatorLayout, scrollAppbar,
//                            fragmentList.get(i).getScrollableView(), 0, scrollAppbar.getTotalScrollRange(), new int[]{0, 0});
//                    onOffsetChanged(scrollAppbar, scrollAppbar.getTotalScrollRange());
                }
                scrollSwipeRefreshLayout.setEnabled(false);
                scrollAppbar.addOnOffsetChangedListener(MainActivity.this);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        scrollPagerSlidingTabStrip.setDoubleClickListener(new DoubleClickListener() {
            @Override
            public void onClick(int position) {
                curTab = position;
                Toast.makeText(MainActivity.this, "click " + position + "-" + position, Toast.LENGTH_SHORT).show();
                resolveToTop();
            }
        });

        scrollViewpager.setCurrentItem(0);
    }

    /**
     * 根据appber的返回，判断此时的tab和banner是位置和显示效果
     */
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
        if (i != scrollOffset) {
            if (curTab == 0) {
                scrollOffsetSquare = i;
            } else {
                scrollOffsetAttention = i;
            }
            scrollOffset = i;
            scrollSwipeRefreshLayout.setEnabled(i == 0);
            scrollViewpager.setIsTop(i == 0);
            float alpha = 1 - (float) Math.abs(i) / (float) appBarLayout.getTotalScrollRange() * 1.0f;
            scrollImageBannerLayout.setAlpha(alpha);
            resolveStripTabStyle(alpha, (int) ((1 - alpha) * tabScroll));
        }
    }


    private void setListener() {

        scrollAppbar.addOnOffsetChangedListener(this);

        fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return fragmentList.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return fragmentList.get(arg0);
            }
        };

        scrollSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (curTab == 0) {
                    fragment1.refresh();
                } else {
                    fragment2.refresh();
                }
            }
        });
        scrollPagerSlidingTabStrip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "click dfsd3333333", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 双击回到顶部
     */
    public void resolveToTop() {
        if (curTab == 0) {
            refreshToTop1();
        } else {
            refreshToTop2();
        }
    }

    private void refreshToTop2() {
//        CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams)
//                scrollAppbar.getLayoutParams()).getBehavior();
//        behavior.onNestedPreScroll(scrollCoordinatorLayout, scrollAppbar,
//                fragmentList.get(1).getScrollableView(), 0, scrollAppbar.getTotalScrollRange(), new int[]{0, 0});
//        onOffsetChanged(scrollAppbar, scrollAppbar.getTotalScrollRange());
//        fragmentList.get(1).changeToTop();
    }

    private void refreshToTop1() {
//        CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams)
//                scrollAppbar.getLayoutParams()).getBehavior();
//        behavior.onNestedPreScroll(scrollCoordinatorLayout, scrollAppbar,
//                fragmentList.get(0).getScrollableView(), 0, scrollAppbar.getTotalScrollRange(), new int[]{0, 0});
//        onOffsetChanged(scrollAppbar, scrollAppbar.getTotalScrollRange());
//        fragmentList.get(0).changeToTop();
    }

//上拉下拉tab和拉远margin
    private void resolveStripTabStyle(float alpha, int margin) {
        margin = 1;
       alpha =0f;
//        scrollPagerSlidingTabStrip.setDividerColor(Color.argb((int) (alpha * 255), 217, 217, 217));//tab中间竖线
        scrollPagerSlidingTabStrip.setIndicatorColor(Color.argb((int) ((1 - alpha) * 255), 251, 151, 63));//tab下分割线
//        scrollPagerSlidingTabStrip.setIndicatorColor(R.color.a);//tab下分割线
//        scrollPagerSlidingTabStrip.setTabPaddingLeftRight(10);
        scrollPagerSlidingTabStrip.setTextColor(0xFF8B8989);//#8B8989、tab的字体颜色未选中
        LinearLayout linearLayout = scrollPagerSlidingTabStrip.getTabsContainer();
        linearLayout.setPadding(margin, linearLayout.getPaddingTop(), margin, linearLayout.getPaddingBottom());


//        if(margin>237)
//        {
//            scrollPagerSlidingTabStrip.setVisibility(View.VISIBLE);
//        }
//        else
//        {
//            scrollPagerSlidingTabStrip.setVisibility(View.GONE);
//        }
        linearLayout.requestLayout();
    }


    private void setViewHeight(View view, int width, int height) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (null == layoutParams)
            return;
        layoutParams.width = width;
        layoutParams.height = height;
        view.setLayoutParams(layoutParams);
    }

}
